package UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;

public class UDPClient {
    public static void main(String[] args) throws IOException {
        // 要发送的信息
        String messg = "我是小李，我想点一个芝士汉堡";
        // 建立Socket
        DatagramSocket socket = new DatagramSocket();
        // 建立收发容器
        byte[] sendData;
        byte[] receiveData = new byte[1024];
        // 发送数据包
        sendData = messg.getBytes();
        InetAddress serverAddress = InetAddress.getByName("localhost");
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, 9999);
        socket.send(sendPacket);
        // 接收数据包
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        socket.receive(receivePacket);
        String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
        System.out.println("Received from Server: " + receivedMessage);
        // 关闭套接字
        socket.close();
    }
}


//import java.io.IOException;
//import java.net.*;
//import java.util.Arrays;
//
//public class UDP.UDPClient {
//    public static void main(String[] args) throws IOException {
//        //要发送的信息
//        String messg = "This is UDP.UDPClient";
//        //建立Socket
//        DatagramSocket socket = new DatagramSocket();
//        //建立收发容器
//        byte[] sendData;
//        byte[] receiveData = new byte[1024];
//        //发送数据包
//        sendData = messg.getBytes();
//        InetAddress serverAddress = InetAddress.getByName("localhost");
//        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, 9999);
//        socket.send(sendPacket);
//        //接收数据包
//        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
//        socket.receive(receivePacket);
//        String receivedMessage  = new String(receivePacket.getData(), 0, receivePacket.getLength());
//        System.out.println("receive from Serve:" + receivedMessage );
//        //关闭资源
//        socket.close();
//    }
//}
